using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using MODI;
using viBook.Common;
using viBook.Filters;
using viBook.Models;
using viBook.Repositories;
using Image = System.Drawing.Image;
using Language = viBook.Common.Language;

namespace viBook.Controllers
{
    public class PagesController : BaseController
    {
        #region Constructors and Repository vars

        private readonly IPageRepository _pageRepository;

        public PagesController(IPageRepository pageRepository)
        {
            _pageRepository = pageRepository;
        }

        #endregion

        [ExtendedAuthentication]
        public ActionResult Edit(int id)
        {
            Page page = _pageRepository.Find(id);
            return View(page);
        }

        [HttpPost, ActionName("Delete")]
        public JsonResult DeleteConfirmed(int id)
        {
            int chapterId;
            _pageRepository.Delete(id, out chapterId);
            _pageRepository.Save();
            return SuccessFeedback;
        }

        [HttpPost, JsonAuthentication]
        public JsonResult SaveTags(List<int> deleted, List<Tag> added, int pageId)
        {
            _pageRepository.SaveTags(deleted, added, pageId);
            return SuccessFeedback;
        }

        [HttpPost, JsonAuthentication]
        public ActionResult ConvertText(string imageUrl, string position, string language)
        {
            string[] imageUrlArr = imageUrl.Split('/');
            string fullImagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, imageUrlArr[1], imageUrlArr[2]);
            string croppedImagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, imageUrlArr[1],
                                                   imageUrlArr[2].Remove(imageUrlArr[2].IndexOf('.')) + "crop_" +
                                                   position + ".bmp");
            return Json(new {success = true, text = CropImage(fullImagePath, croppedImagePath, position, language)});
        }

        private static string CropImage(string fullImg, string croppedImg, string position, string language)
        {
            string[] positionArr = position.Split('_');

            var myBmp = (Bitmap) Image.FromFile(fullImg);

            double resizePercent = myBmp.Width/(double) Constant.DefaultImageWith;

            double y = int.Parse(positionArr[0])*resizePercent;
            double x = int.Parse(positionArr[1])*resizePercent;
            double w = int.Parse(positionArr[2])*resizePercent;
            double h = int.Parse(positionArr[3])*resizePercent;
            var rectangle = new Rectangle((int) y, (int) x, (int) w, (int) h);
            var bmpImage = new Bitmap(fullImg);
            Bitmap bmpCrop = myBmp.Clone(rectangle, bmpImage.PixelFormat);
            bmpCrop.Save(croppedImg, ImageFormat.Bmp);
            try
            {
                var md = new Document();
                md.Create(croppedImg);
                MiLANGUAGES languages = ConvertLanguageFromString(language);
                md.OCR(languages, true, true);
                string strText = String.Empty;

                var image = (MODI.Image) md.Images[0];
                Layout layout = image.Layout;

                for (int i = 0; i < layout.Words.Count; i++)
                {
                    var word = (Word) layout.Words[i];
                    if (strText.Length > 0)
                    {
                        strText += " ";
                    }
                    strText += word.Text;
                }
                md.Close(false);
                return (strText);
            }
            catch (Exception ex)
            {
                if (ex is NotSupportedException)
                    return Constant.NotSupportedLanguageErrorMessage;
                return Constant.GeneralConvertErrorMessage;
            }
            finally
            {
                Helpers.Helpers.DeleteCropedFile(croppedImg);
            }
        }

        private static MiLANGUAGES ConvertLanguageFromString(string langstring)
        {
            MiLANGUAGES language = MiLANGUAGES.miLANG_SYSDEFAULT;
            foreach (Language language1 in Constant.Languages)
            {
                if (language1.GoogleCodeLanguage.Equals(langstring))
                    return language1.ModiCodeLanguage;
            }
            return language;
        }
    }
}